package com.qianfan.qfcall.network

import com.qianfan.qfcall.network.response.BaseResponse
import com.sum.network.error.ApiException
import com.wxq.workpad.utils.log.LogUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException

/**
 * IO中处理请求
 */
suspend fun <T> requestResponseThrowException(requestCall: suspend () -> BaseResponse<T>?): T? {
    val response = withContext(Dispatchers.IO) {
            requestCall()
    }
    return if (response == null) null else if (!response.isFailed) {
        response.data
    } else {
        throw ApiException(response.code, response.msg)
    }
}


//返回实体类自己在协程中手动处理 when (response) {
//                is ApiResponse.Ok -> aboutUsFlow.emit(response.data)
//                is ApiResponse.BizError -> {}
//                is ApiResponse.OtherError -> {
//                    LogUtils.d("error:${response.throwable.message}")
//                }
//            }
suspend fun <T : Any> request(request: suspend () -> BaseResponse<T>): ApiResponse<T> {
    try {
        val response=   withContext(Dispatchers.IO) {
            request.invoke()
        }
        return when (response.code) {
            200 -> {
                ApiResponse.Ok(response.data)
            }
            else -> {
                ApiResponse.BizError(response.code, response.msg)
            }

        }
    } catch (e: Exception) {
        return if (e is HttpException) {
            ApiResponse.OtherError(
                e.code(),
                e
            )
        } else {
            val errorString = "cause==>${e.cause}\nmessage==>${e.message}"
            LogUtils.d("kt net error:$errorString")
            ApiResponse.OtherError(0, e)
        }
    }
}
